
package it.csttech.date;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

import javax.ws.rs.BadRequestException;

import org.apache.commons.validator.routines.FloatValidator;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

/**
 * This class is a module of the object mapper whose purpose is to deserialize a
 * JSON string into a float according to the request locale
 * 
 * @author marcello.felappi
 * @author marco.dalena
 */
public class FloatJsonDeserializer extends JsonDeserializer<Float> {

	/**
	 * locale of the request
	 */
	private Locale locale;

	/**
	 * Method representing a constructor for the FloatJsonDeserializer class
	 * 
	 * @param locale
	 */
	public FloatJsonDeserializer(Locale locale) {

		this.locale = locale;
	}

	/**
	 * This method is used to deserialize a JSON string into a java float object
	 * according to the locale of the request
	 * 
	 * @param parser
	 *            - JsonParser parser used by Jackson to parse the json input
	 * @param context
	 *            - DeserializationContext
	 * @throws IOException
	 *             - thrown due to i/o issues
	 * @throws JsonProcessingException
	 *             - thrown in case of problem during the parsing of the json
	 * @throws BadRequestException
	 *             - thrown because of an error during the parsing of the float
	 *             because of a wrong format
	 * @return the float converted from the input string according to the locale
	 *         of the request
	 */
	@Override
	public Float deserialize(JsonParser parser, DeserializationContext ctx)
		throws IOException, JsonProcessingException {

		String input = parser.getText();
		NumberFormat format = DecimalFormat.getInstance(locale);
		FloatValidator validator = new FloatValidator();

		try {
			if (validator.validate(
				input, ((DecimalFormat) format).toPattern(), locale) != null) {
				Number number = format.parse(input);
				return number.floatValue();
			}
			else
				throw new BadRequestException();
		}
		catch (ParseException e) {
			throw new BadRequestException();
		}

	}
}
